from django.shortcuts import render
from .functions import *
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.db import transaction


# 分类菜品展示
def dishes(request):
    # 从数据库获取菜品分类后的菜品对象
    try:
        dishes = Dishes.objects.get_dishes(request)
    except:
        pass
    return render(request, 'dishes/dishes.html', locals())

# 单个菜品页面
def one_dish(request):
    # 从数据库获取这个菜品
    try:
        dish = Dishes.objects.get_one_dish(request)
        dish_responses = DishResponse.objects.get_5_response(dish.id,0)
    except:
        pass
    mess = get_messages(request)
    return render(request, 'dishes/dish.html', locals())

# 所有菜品页面
def all_dishes(request,param):
    # 获取所有菜品
    try:
        all_dishes = Dishes.objects.all().order_by("-"+param)
    except:
        pass
    else:
        # 创建分页器
        paginator = Paginator(all_dishes,12)
        # 获取当前页码
        page_now = get(request,"page","1")
        # 当前页面商品
        dishes = paginator.page(page_now)
    return render(request,'dishes/all_dishes.html',locals())


# 菜品评论表单提交
def response_form(request):
    # 验证用户输入数据合法性
    if check_response_input(request):
        # 创建保存点
        save_point = transaction.savepoint()
        try:
            # 存入数据库
            DishResponse.objects.save_response(request)
            # 更新评论数
            # 更改菜品评论数
            Dishes.objects.update_dish_response_num(request)
            # 提交操作
            transaction.savepoint_commit(save_point)
            return JsonResponse({"ret":1})
        except:
            # 如果操作出错，滚回去
            transaction.savepoint_rollback(save_point)
            pass

# 点赞功能,ajax
def dish_praise(request):
    try:
        new_praise = Dishes.objects.update_dish_praise(request)
        return JsonResponse({"ret":new_praise})
    except:
        pass


# 查看更多评论
def show_more_response(request):
    dish_id = get(request, "dish_id")
    re_ok_num = get(request,"re_ok_num")
    try:
        # 从数据库再查出五条数据返回
        more_responses = DishResponse.objects.get_5_response(dish_id,re_ok_num)
    except:
        pass
    else:
        if more_responses:
            # 组装数据为json格式
            re_list = make_json(more_responses)
            return JsonResponse({"ret": re_list})
        else:
            return JsonResponse({"ret":0})
